package com.sky.web.admin;

import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/report")
public class ReportController {

    @Autowired
    private ReportService reportService;

    //营业额统计
    @GetMapping("/turnoverStatistics")
    public Result turnoverStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
        TurnoverReportVO vo = reportService.turnoverStatistics(begin,end);
        return Result.success(vo);
    }

    // 用户统计
    @GetMapping("/userStatistics")
    public Result userStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
        UserReportVO vo =reportService.userStatistics(begin,end);
        return Result.success(vo);
    }

    //订单统计
    @GetMapping("/ordersStatistics")
    public Result ordersStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
        OrderReportVO vo =reportService.ordersStatistics(begin,end);
        return Result.success(vo);
    }

    //销量排名Top10
    @GetMapping("/top10")
    public Result top10(
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate end
    ) {
      SalesTop10ReportVO vo=reportService.top10(begin,end);
        return Result.success(vo);
    }

    //报表导出
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        //BusinessDataVO   List<BusinessDataVO>
        //1. 构建日期列表
        /**
         *  begin,30天前 end,昨天,  这样保证数据的一致性,今天上午导出的数据,下午也能用
         */
        List<LocalDate> dateList = getDateList(LocalDate.now().minusDays(30),LocalDate.now().minusDays(1));//通过方法获得30天的list日期集合
        //2. 声明数据变量
        List<BusinessDataVO> list = new ArrayList<>(); //明细列表
        double turnover = 0;//营业额
        double orderCompletionRate = 0;//订单完成率
        int newUsers = 0;//新增用户数
        int validOrderCount = 0;//有效订单数
        double unitPrice = 0;//平均客单价
        int total = 0; //总记录数

        //3. 遍历查询每天的数据
        for (LocalDate date : dateList) {
            BusinessDataVO businessDataVO = reportService.businessData(date);
            businessDataVO.setDate(date);
            list.add(businessDataVO);
            //统计加和
            turnover += businessDataVO.getTurnover();//累加营业额
            orderCompletionRate += businessDataVO.getOrderCompletionRate();//累加订单完成率
            newUsers += businessDataVO.getNewUsers();//累加新增用户数
            validOrderCount += businessDataVO.getValidOrderCount();//累加有效订单数
            unitPrice += businessDataVO.getUnitPrice();//累加平均客单价
        }

        //对完成率和客单价做处理
        orderCompletionRate = orderCompletionRate / 30;
        unitPrice = unitPrice / 30;

        //4. 构建BusinessDataVO对象
        BusinessDataVO businessDataVO = BusinessDataVO.builder()
                .beginTime(LocalDate.now().minusDays(30))//30天前
                .endTime(LocalDate.now().minusDays(1))//昨天
                .turnover(turnover)//总营业额
                .orderCompletionRate(orderCompletionRate)//订单完成率
                .newUsers(newUsers)//新增用户数
                .validOrderCount(validOrderCount)//有效订单数
                .unitPrice(unitPrice)//平均客单价
                .total(list.size())//总记录数
                .build();

        //5. 填充报表
        //5-1 获取模板文件
        File templateFileName = new ClassPathResource("template/运营数据报表模板.xlsx").getFile();
        //5-2 填充
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(templateFileName).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            //填充list集合
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
            excelWriter.fill(list, fillConfig, writeSheet);
            //填充对象
            excelWriter.fill(businessDataVO, writeSheet);
        }
    }

    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        LocalDate dateIndex = begin;//日期指针
        while (!dateIndex.isAfter(end)) {
            dateList.add(dateIndex);
            dateIndex = dateIndex.plusDays(1);//指针后移1天
        }

        return dateList;
    }

}
